package com.flyme.module.base.provider.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.api.SysStudentRemoteService;
import com.flyme.module.base.client.entity.SysBalance;
import com.flyme.module.base.client.entity.SysBalancelog;
import com.flyme.module.base.client.entity.SysIntegralrecord;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.exam.provider.service.ExamRecordService;
import com.flyme.module.file.client.entity.SysCourseComment;
import com.flyme.module.file.provider.service.SysCourseCommentService;
import com.flyme.module.order.provider.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户信息
 *
 * @author zyf
 */
@Api(tags = "学员管理")
@RestController
public class SysStudentController extends BaseController<SysUserService, SysUser> implements SysStudentRemoteService {

    @Autowired
    private SysAccountService sysAccountService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysIntegralrecordService integralrecordService;
    @Autowired
    private SysBalancelogService balancelogService;
    @Autowired
    private SysBalanceService balanceService;
    @Autowired
    private SysVipService vipService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysCourseCommentService courseCommentService;
    @Autowired
    private SysFeedbackService feedbackService;
    @Autowired
    private SysCreditbankService creditbankService;
    @Autowired
    private ExamRecordService examRecordService;
    @Autowired
    private SysOperationlogService sysOperationlogService;

    /**
     * 学员列表
     *
     * @return
     */
    @ApiOperation(value = "学员列表", notes = "学员列表")
    @Override
    public ResultBody list(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName","nickName", "avatar","company.compName", "dept.deptName","mobile", "email", "v.createTime vipBugTime", "schoolNum",
            "v.expiryDate", "birthday","age", "sex", "userType", "positionName", "u.status", "u.createTime", "b.amount", "b.integral", "u.idCard");
        cq.like("u.userName", user.getUserName());
        cq.like("u.mobile", user.getMobile());
        cq.like("company.compName", user.getCompany());
        cq.eq("u.userType", user.getUserType());
        cq.gt("u.createTime", user.getStartDate());
        cq.lt("u.createTime", user.getEndDate());
        cq.createAlias("vip", "v");
        cq.createAlias("dept", "dept");
        cq.createAlias("company", "company");
        cq.createAlias("balance", "b");
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 学员列表
     *
     * @return
     */
    @ApiOperation(value = "学员列表", notes = "学员列表")
    @Override
    public ResultBody list2(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName","nickName", "avatar", "mobile", "email", "schoolNum", "birthday","age", "sex", "u.learnCenter", "u.licenseStatus",
                "u.status", "u.idCard", "u.nationality", "u.nation", "u.cityString", "u.address", "u.cardNoImg", "u.cardNoImg2", "u.cardLiveImg");
        cq.like("u.userName", user.getUserName());
        cq.like("u.mobile", user.getMobile());
        cq.eq("u.userType", user.getUserType());
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    @ApiOperation(value = "删除学员", notes = "删除学员")
    @Override
    public ResultBody delByIds(@RequestParam Long[] ids) {
        List<String> list = new ArrayList<>();
        //删除前判断用户是否有订单等记录
        if(ids.length>0){
            for(Long userId : ids){
                //订单
                Integer orderNum = orderService.countByUser(userId);
                //课程评论
                Integer commenNum = courseCommentService.countByUser(userId);
                //留言反馈
                Integer feedbackNum = feedbackService.countByUser2(userId);
                //学分转换
                Integer cbNum = creditbankService.countByUser(userId);
                //答题记录
                Integer examNum = examRecordService.countByUser(userId);
                if(orderNum>0 || commenNum>0 || feedbackNum>0 || cbNum>0 || examNum>0){
                    return ResultBody.failed("该用户有相关记录，无法删除");
                }
                SysUser user = sysUserService.getById(userId);
                list.add(user.getUserName());
            }
        }
        sysAccountService.deleteByIds(ids);
        Boolean tagUser = sysUserService.delByIds(ids);
        if(tagUser){
            for(String userName : list){
                sysOperationlogService.addOperation("删除用户："+userName);
            }
        }
        return ResultBody.success(tagUser);
    }


    /**
     * 更新系统用户
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "更新系统用户", notes = "更新系统用户")
    @Override
    public ResultBody updateUser(@ModelAttribute SysUser user) {
        SysUser oldUser = bizService.getById(user.getId());
        if (!user.getMobile().equals(oldUser.getMobile())) {//当手机号变化
            //当用户手机号发生改变时
            SysUser accountInfo = bizService.findByMobile(user.getMobile());
            if (ObjectUtils.isNotEmpty(accountInfo)) {//该手机号已注册
                return ResultBody.failed("该手机号已注册");
            }
            bizService.updateMobile(user.getId(), oldUser.getMobile(), user.getMobile());
        }
        Boolean tag = bizService.saveOrUpdate(user);
        return ResultBody.success("更新成功").setData(tag);
    }

    @Override
    public ResultBody getStudent(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        return ResultBody.success(user);
    }

    /**
     * 更新状态
     *
     * @param status
     * @return
     */
    @ApiOperation(value = "设置状态", notes = "设置状态")
    @Override
    public ResultBody setStatus(@RequestParam Long id, @RequestParam Integer status) {
        boolean result = bizService.update(new UpdateWrapper<SysUser>().set("status", status).eq("id", id));
        return ResultBody.ok("设置成功").setData(result);
    }

    /**
     * 赠送积分
     */
    @ApiOperation(value = "赠送积分", notes = "赠送积分")
    public ResultBody addScore(@RequestParam Long[] ids, @RequestParam Integer score) {
        List<SysIntegralrecord> list = new ArrayList<>();
        List<SysBalance> blist = new ArrayList<>();
        for (Long id : ids) {
            SysIntegralrecord record = new SysIntegralrecord();
            record.setAccountId(id);
            record.setIntegral(score);
            record.setRecordBody("平台赠送");
            record.setRecordCode("scoreSys");
            list.add(record);
            SysBalance balance = balanceService.getById(id);
            balance.setIntegral(balance.getIntegral() + score);
            blist.add(balance);
            SysUser user = sysUserService.getById(id);
            sysOperationlogService.addOperation("赠送用户积分："+user.getUserName()+"  "+score+"积分");
        }
        boolean b = balanceService.updateBatchById(blist);
        if (b) {
            boolean tag = integralrecordService.saveBatch(list);
        }
        return ResultBody.ok("赠送成功").setData(b);
    }

    /**
     * 赠送学习币
     */
    @ApiOperation(value = "赠送学习币", notes = "赠送学习币")
    public ResultBody addIntegral(@RequestParam Long[] ids, @RequestParam String score) {
        List<SysBalancelog> list = new ArrayList<>();
        BigDecimal integral = new BigDecimal(score);
        List<SysBalance> blist = new ArrayList<>();
        for (Long id : ids) {
            SysBalancelog record = new SysBalancelog();
            record.setBalanceId(id);
            record.setAccountInfoId(id);
            record.setTitle("平台赠送");
            record.setBody("平台赠送");
            record.setAmount(integral);
            record.setType(1);
            list.add(record);
            SysBalance balance = balanceService.getById(id);
            balance.setAmount(balance.getAmount().add(integral));
            blist.add(balance);
            SysUser user = sysUserService.getById(id);
            sysOperationlogService.addOperation("赠送用户学习币："+user.getUserName()+"  "+integral+"学习币");
        }
        boolean b = balanceService.updateBatchById(blist);
        if (b) {
            boolean tag = balancelogService.saveBatch(list);
        }
        return ResultBody.ok("赠送成功").setData(b);
    }

    /**
     * 用户积分记录
     */
    @ApiOperation(value = "积分记录", notes = "积分记录")
    public ResultBody scoreList(@ModelAttribute PagerInfo pagerInfo, @RequestParam Long userId) {
        String accountId = userId.toString();
        PqGrid list = integralrecordService.selectByUser2(accountId, pagerInfo);
        return ResultBody.success(list);
    }

    /**
     * 学习币充值记录记录
     */
    @ApiOperation(value = "学习币记录", notes = "学习币记录")
    public ResultBody amountList(@ModelAttribute PagerInfo pagerInfo, @RequestParam Long userId) {
        String accountId = userId.toString();
        PqGrid list = balancelogService.selectByUser(pagerInfo, userId);
        return ResultBody.success(list);
    }

    /**
     * 添加用户vip
     */
    @ApiOperation(value = "添加用户VIP", notes = "添加用户VIP")
    public ResultBody addUserVip(@RequestParam Long userId, @RequestParam Integer vipTime) {
        boolean tag = vipService.addVip(userId, vipTime);
        if(tag){
            SysUser user = sysUserService.getById(userId);
            sysOperationlogService.addOperation("赠送用户VIP："+user.getUserName()+"  "+vipTime+"个月VIP会员");
        }
        return ResultBody.success(tag);
    }

}
